package com.bookshop.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.autoconfigure.quartz.QuartzTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author g2l
 * @create 2024-01-18 18:46
 */
@Configuration
public class DataSourceConfiguration {

    @Resource
    private Environment environment;

    /**
     * 为quartz的任务和触发器单独配置一个数据源  @QuartzDataSource注解用于声明quartz使用这个数据源
     * @return
     */
    @Bean
    @QuartzDataSource
    public DataSource quartzDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.druid.driver-class-name"));
        druidDataSource.setUsername(environment.getProperty("spring.datasource.druid.username"));
        druidDataSource.setPassword(environment.getProperty("spring.datasource.druid.password"));
        druidDataSource.setUrl(environment.getProperty("spring.quartz.url"));
        return druidDataSource;
    }

    // 这里需要单独配业务数据源并加上@Primary注解，使得quartz数据源和业务数据源分开
    @Bean
    @Primary
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.druid.driver-class-name"));
        druidDataSource.setUsername(environment.getProperty("spring.datasource.druid.username"));
        druidDataSource.setPassword(environment.getProperty("spring.datasource.druid.password"));
        druidDataSource.setUrl(environment.getProperty("spring.datasource.druid.url"));
        return druidDataSource;
    }

    /**
     * 为quartz的数据源配置事务管理器  @QuartzTransactionManager注解用于声明quartz使用这个事务管理器
     * @param quartzDataSource
     * @return
     */
    @Bean
    @QuartzTransactionManager
    public TransactionManager quartzTransactionManager(@Qualifier("quartzDataSource") DataSource quartzDataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(quartzDataSource);
        return transactionManager;
    }

}
